﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using Weixin.Utils;
using Weixin.Entity.Weixin;

namespace Weixin.Web
{
    /// <summary>
    ///WX 的摘要说明
    /// </summary>
    public class WX
    {
        string _Signature, _Timestamp, _Nonce, _Echostr;
        public WX()
        {
            //暂无操作
        }
        public WX(string signature, string timestamp, string nonce, string echostr)
        {
            _Signature = signature;
            _Timestamp = timestamp;
            _Nonce = nonce;
            _Echostr = echostr;
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        /// 将token、timestamp、nonce三个参数进行字典序排序
        /// 将三个参数字符串拼接成一个字符串进行sha1加密
        /// 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。
        /// <returns></returns>
        public bool CheckSignature()
        {
            string Token = ConfigHelper.GetConfigString("Token");
            string[] ArrTmp = { Token, _Timestamp, _Nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == _Signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 返回接入验证通过有效值
        /// </summary>
        /// <param name="echostr"></param>
        public void Valid()
        {
            if (!string.IsNullOrEmpty(_Echostr))
            {
                HttpContext.Current.Response.Write(_Echostr);
                HttpContext.Current.Response.End();
            }
        }
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <returns>token值</returns>
        private string GetToken()
        {
            string result = string.Empty;

            AccessToken accessToken = CacheManager<AccessToken>.GetFromCache("token");
            if (accessToken == null)
            {
                string url = "https://api.weixin.qq.com/cgi-bin/token";
                string appId = ConfigHelper.GetConfigString("appId");
                string appSecret = ConfigHelper.GetConfigString("appSecret");
                string data = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
                string content = WebRequestHelper.GetData(url, data);
                if (content.Contains("access_token"))
                {
                    accessToken = JsonHelper.DeserializeJson<AccessToken>(content);
                    CacheManager<AccessToken>.AddToCache("token", accessToken, 60);
                    Logger.Log4Net.Info("获取Token成功：" + content);
                    result = accessToken.access_token;
                }
                else
                {
                    ErrorCode errorCode = JsonHelper.DeserializeJson<ErrorCode>(content);
                    Logger.Log4Net.Info("获取Token失败：" + content);
                }
            }
            else
            {
                result = accessToken.access_token;
            }

            return result;
        }

        private string GetJsApiTicket(string token)
        {
            string result = string.Empty;

            JsApiTicket jsApiTicket = CacheManager<JsApiTicket>.GetFromCache("jsapi");
            if (jsApiTicket == null)
            {
                string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
                string content = WebRequestHelper.GetData(url, "access_token=" + token + "&type=jsapi");
                if (content.Contains("ticket"))
                {
                    jsApiTicket = JsonHelper.DeserializeJson<JsApiTicket>(content);
                    CacheManager<JsApiTicket>.AddToCache("jsapi", jsApiTicket, 60);
                    Logger.Log4Net.Info("获取jsapi成功：" + content);
                    result = jsApiTicket.ticket;
                }
                else
                {
                    ErrorCode errorCode = JsonHelper.DeserializeJson<ErrorCode>(content);
                    Logger.Log4Net.Info("获取jsapi失败：" + content);
                }
            }
            else
            {
                result = jsApiTicket.ticket;
            }

            return result;
        }

        /// <summary>
        /// 创建随机字符串
        /// </summary>
        /// <returns></returns>
        private string CreateNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            Random rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        /// <summary>
        /// 创建时间戳
        /// </summary>
        /// <returns></returns>
        private string GetTimeStamp()
        {
            return Convert.ToString(ConvertDateTimeInt(DateTime.Now));
        }

        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>double</returns>  
        public int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = Convert.ToInt32((time - startTime).TotalSeconds);
            return intResult;
        }

        /// <summary>
        /// 返回接收微信消息实体
        /// </summary>
        /// <param name="receiveData"></param>
        /// <returns></returns>
        public WXReceiveData GetWeixinMessage(string receiveData)
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(receiveData);
            XmlNode node = xml.SelectSingleNode("xml");

            WXReceiveData wxreceiveData = new WXReceiveData();
            wxreceiveData.ToUserName = node.SelectSingleNode("ToUserName").InnerText;
            wxreceiveData.FromUserName = node.SelectSingleNode("FromUserName").InnerText;
            wxreceiveData.CreateTime = node.SelectSingleNode("CreateTime").InnerText;
            wxreceiveData.MsgType = node.SelectSingleNode("MsgType").InnerText.ToLower();
            if (wxreceiveData.MsgType == "event")
            {
                wxreceiveData.Event = node.SelectSingleNode("Event").InnerText.ToLower();
                if (wxreceiveData.Event == "subscribe" || wxreceiveData.Event == "scan")
                {
                    wxreceiveData.EventKey = node.SelectSingleNode("EventKey").InnerText;
                    //wxreceiveData.Ticket = node.SelectSingleNode("Ticket").InnerText;
                }
                if (wxreceiveData.Event == "click" || wxreceiveData.Event == "view")
                {
                    wxreceiveData.EventKey = node.SelectSingleNode("EventKey").InnerText;
                }
            }

            if (wxreceiveData.MsgType == "text")
            {
                wxreceiveData.Content = node.SelectSingleNode("Content").InnerText;
                wxreceiveData.MsgId = long.Parse(node.SelectSingleNode("MsgId").InnerText);
            }
            if (wxreceiveData.MsgType == "image")
            {
                wxreceiveData.PicUrl = node.SelectSingleNode("PicUrl").InnerText;
                wxreceiveData.MediaId = node.SelectSingleNode("MediaId").InnerText;
                wxreceiveData.MsgId = long.Parse(node.SelectSingleNode("MsgId").InnerText);
            }
            if (wxreceiveData.MsgType == "voice")
            {
                wxreceiveData.MediaId = node.SelectSingleNode("MediaId").InnerText;
                wxreceiveData.Format = node.SelectSingleNode("Format").InnerText;
                wxreceiveData.MsgId = long.Parse(node.SelectSingleNode("MsgId").InnerText);
            }
            if (wxreceiveData.MsgType == "location")
            {

            }
            if (wxreceiveData.MsgType == "link")
            {
                wxreceiveData.Title = node.SelectSingleNode("Title").InnerText;
                wxreceiveData.Description = node.SelectSingleNode("Description").InnerText;
                wxreceiveData.Url = node.SelectSingleNode("Url").InnerText;
            }

            return wxreceiveData;
        }

        /// <summary>
        /// 返回被动响应消息字符串
        /// </summary>
        /// <param name="sendData"></param>
        /// <returns></returns>
        public string SendDataMessage(WXSendData sendData)
        {
            string result = string.Empty;
            if (sendData.MsgType == "text")
            {
                result = @"<xml>
                           <ToUserName><![CDATA[" + sendData.ToUserName + @"]]></ToUserName>
                           <FromUserName><![CDATA[" + sendData.FromUserName + @"]]></FromUserName>
                           <CreateTime>" + sendData.CreateTime + @"</CreateTime>
                           <MsgType><![CDATA[text]]></MsgType>
                           <Content><![CDATA[" + sendData.Content + @"]]></Content>
                      </xml>";
            }
            if (sendData.MsgType == "image")
            {

            }
            if (sendData.MsgType == "news")
            {

            }

            return result;
        }

        public bool CreateCustomerMenu()
        {
            string token = GetToken();

            if (token != "")
            {
                string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;
                //string data = "{\"button\":"
                //                + "[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"}"
                //                + ",{\"type\":\"click\",\"name\":\"歌手简介\",\"key\":\"V1001_TODAY_SINGER\"}"
                //                + ",{\"name\":\"菜单\",\"sub_button\":"
                //                     + "[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"}"
                //                     + ",{\"type\":\"view\",\"name\":\"视频\",\"url\":\"http://v.qq.com/\"}"
                //                     + ",{\"type\":\"click\",\"name\":\"赞一下我们\",\"url\":\"http://v.baidu.com/\"}"
                //                     + "]"
                //                  + "}"
                //                + "]"
                //             + "}";
                string data = "{\"button\":["
                                + "{\"name\":\"税务咨询\",\"sub_button\":"
                                     + "[{\"type\":\"view\",\"name\":\"专家团队\",\"url\":\"http://wx.china-tax.org/person.aspx?typeId=27\"}"
                                     + ",{\"type\":\"view\",\"name\":\"税务顾问\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=103\"}"
                                     + ",{\"type\":\"view\",\"name\":\"独家优势\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=99\"}"
                                     + ",{\"type\":\"view\",\"name\":\"我要提问\",\"url\":\"http://wx.china-tax.org/question.aspx\"}"
                                     + "]"
                                  + "}"
                                + ",{\"name\":\"培训课程\",\"sub_button\":"
                                     + "[{\"type\":\"view\",\"name\":\"公开课\",\"url\":\"http://wx.china-tax.org/article.aspx?typeId=101\"}"
                                     + ",{\"type\":\"view\",\"name\":\"内训课\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=100\"}"
                                     + ",{\"type\":\"view\",\"name\":\"公益活动\",\"url\":\"http://wx.china-tax.org/article.aspx?typeId=102\"}"
                                     + ",{\"type\":\"view\",\"name\":\"精彩回顾\",\"url\":\"http://wx.china-tax.org/news.aspx?typeId=104\"}"
                                     + ",{\"type\":\"view\",\"name\":\"学员寄语\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=105\"}"
                                     //+ ",{\"type\":\"view\",\"name\":\"立即报名\",\"url\":\"http://wx.china-tax.org/online.aspx\"}"
                                     + "]"
                                  + "}"
                                + ",{\"name\":\"加盟合作\",\"sub_button\":"
                                     + "[{\"type\":\"view\",\"name\":\"税务咨询师\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=97\"}"
                                     + ",{\"type\":\"view\",\"name\":\"招合伙人\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=106\"}"
                                     + ",{\"type\":\"view\",\"name\":\"创业就业\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=107\"}"
                                     + ",{\"type\":\"view\",\"name\":\"了解我们\",\"url\":\"http://wx.china-tax.org/detail.aspx?typeId=108\"}"
                                     + ",{\"type\":\"view\",\"name\":\"免费注册\",\"url\":\"http://wx.china-tax.org/register.aspx\"}"
                                     + "]"
                                  + "}"
                                + "]"
                             + "}";
                string content = WebRequestHelper.PostData(url, data);
                if (content != "")
                {
                    Logger.Log4Net.Info("创建菜单结果：" + content);
                    ErrorCode errorCode = JsonHelper.DeserializeJson<ErrorCode>(content);
                    if (errorCode.errcode == "0")
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public bool DeleteCustomerMenu()
        {
            string token = GetToken();
            if (token != "")
            {
                string url = "https://api.weixin.qq.com/cgi-bin/menu/delete";
                string data = "access_token=" + token;
                string content = WebRequestHelper.GetData(url, data);
                if (content != "")
                {
                    ErrorCode errorCode = JsonHelper.DeserializeJson<ErrorCode>(content);
                    if (errorCode.errcode == "0")
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public string GetCustomerMenu()
        {
            string token = GetToken();
            Logger.Log4Net.Info("获取token:" + token);
            if (token != "")
            {
                string url = "https://api.weixin.qq.com/cgi-bin/menu/get";
                string data = "access_token=" + token;
                string content = WebRequestHelper.GetData(url, data);

                return content;
            }

            return "";
        }

        public string[] GetJSSDK(string url)
        {
            string noncestr = CreateNonceStr();
            string jsapi_ticket = GetJsApiTicket(GetToken());
            string timestamp = GetTimeStamp();
            string signature = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url, "sha1").ToLower();

            return new string[5] { noncestr, jsapi_ticket, timestamp, signature, url };
        }
    }
}